package com.lanou3g.zjl.chating.home.setting;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.BusLineSearch;
import com.baidu.mapapi.search.busline.OnGetBusLineSearchResultListener;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.lanou3g.zjl.chating.home.setting.overlayutil.BusLineOverlay;
import com.lanou3g.zjl.chating.home.setting.overlayutil.PoiOverlay;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * Created by dllo on 15/12/1.
 */
public class BaiduMapActivity extends BaseActivity implements OnGetPoiSearchResultListener, OnGetBusLineSearchResultListener, BaiduMap.OnMapClickListener {
    @Bind(R.id.positionAddress)
    TextView positionAddress;//显示当前位置
    @Bind(R.id.bmapView)
    MapView mapView;
    @Bind(R.id.addressKeywords)
    EditText addressKeywords;

    private BaiduMap baiduMap;//操作地图的
    private LocationClient locationClient;//定位对象
    private PoiSearch mPoiSearch = null;
    private String currentCity;//当前所在城市
    private PoiSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private BusLineOverlay overlay; // 公交路线绘制对象
    private BusLineSearch mBusLineSearch = null;

    @Override
    protected int getLayout() {

        return R.layout.baidu_map_view;
    }

    @Override
    protected void initData() {

        initView();
    }

    //查找附近的东西
    @OnClick(R.id.search_address)
    void test() {

//        mPoiSearch.searchInCity((new PoiCitySearchOption())
//                .city(currentCity)
//                .keyword(addressKeywords.getText().toString())
//                .pageNum(10));
        if(!TextUtils.isEmpty(positionAddress.getText())){
            //将地址返回聊天界面
            Intent intent = new Intent();
            intent.putExtra("location",positionAddress.getText().toString());
            setResult(400, intent);
            finish();
        }
    }

    //公交路线
    @OnClick(R.id.gotoHereByBus)
    void busLine() {

        mSearch.searchInCity((new PoiCitySearchOption()).city(currentCity)
                .keyword(addressKeywords.getText().toString()));
    }

    //查询结果监听
    public void onGetPoiResult(PoiResult result) {
        if (result == null
                || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(BaiduMapActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            baiduMap.clear();
            PoiOverlay overlay = new MyPoiOverlay(baiduMap);
            baiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(result);
            overlay.addToMap();
            overlay.zoomToSpan();
            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(BaiduMapActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(BaiduMapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(BaiduMapActivity.this, poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    //公交路线查询结果监听
    @Override
    public void onGetBusLineResult(BusLineResult busLineResult) {
        if (busLineResult == null || busLineResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(BaiduMapActivity.this, "抱歉，未找到结果",
                    Toast.LENGTH_LONG).show();
            return;
        }
        baiduMap.clear();
        overlay.removeFromMap();
        overlay.setData(busLineResult);
        overlay.addToMap();
        overlay.zoomToSpan();
        Toast.makeText(BaiduMapActivity.this, busLineResult.getBusLineName(),
                Toast.LENGTH_SHORT).show();
    }

    //在地图上点击的监听
    @Override
    public void onMapClick(LatLng latLng) {
        baiduMap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }


    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            //if (poi.hasCaterDetails) {
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            //}
            return true;
        }
    }

    private void initView() {
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(BaiduMapActivity.this);
        //公交路线
        mSearch = PoiSearch.newInstance();
        mSearch.setOnGetPoiSearchResultListener(this);
        overlay = new BusLineOverlay(baiduMap);
        mBusLineSearch = BusLineSearch.newInstance();
        mBusLineSearch.setOnGetBusLineSearchResultListener(this);

        baiduMap = mapView.getMap();//获得baiduMap对象
        baiduMap.setMyLocationEnabled(true);//开启定位
        baiduMap.setOnMapClickListener(this);
        baiduMap.setOnMarkerClickListener(overlay);
        locationClient = new LocationClient(this);
        //注册定位监听
        locationClient.registerLocationListener(new MyLocationListenner());
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(1000);//每隔一秒定位一次
        option.setCoorType("bd09ll");
        option.setOpenGps(true);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        locationClient.setLocOption(option);
        locationClient.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
        locationClient.stop();
        mPoiSearch.destroy();
        mSearch.destroy();
        mBusLineSearch.destroy();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            currentCity = location.getCity();
            positionAddress.setText(location.getAddrStr());
            // map view 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
//            if (isFirstLoc) {
//                isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(u);
//            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

}
